package com.xbongbong.pro.message.service.impl;

import com.alibaba.dingtalk.openapi.helper.AuthHelper;
import com.alibaba.dingtalk.openapi.helper.DingtalkWorkrecordHelper;
import com.alibaba.dingtalk.openapi.helper.Env;
import com.alibaba.dingtalk.openapi.vo.workrecord.FormComponentValueVo;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveFakeProcessInstance;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveFakeProcessInstanceRequest;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveTask;
import com.alibaba.dingtalk.openapi.vo.workrecord.SaveTaskRequest;
import com.alibaba.dingtalk.openapi.vo.workrecord.TaskTopVo;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.message.domain.entity.PushEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.MessageErrorCodeEnum;
import com.xbongbong.pro.message.service.DingtalkWorkrecordMessage;
import com.xbongbong.saas.domain.entity.ext.CommunicatePlanEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 钉钉待办消息
 * @author xingxing.xiao
 * @date 2019/07/19 10:34
 */
@Service("dingtalkWorkrecordMessage")
public class DingtalkWorkrecordMessageImpl implements DingtalkWorkrecordMessage {

    private static final Logger LOG = LoggerFactory.getLogger(DingtalkWorkrecordMessageImpl.class);

    @Resource
    private AuthHelper authHelper;

    /**
     * 创建钉钉待办实例
     * @param corpid
     * @return
     * @throws XbbException
     */
    @Override
    public DingtalkWorkrecordHelper.ProcessInstanceResponse createWorkrecordInstance(String corpid, String dingtalkProcessCode, PushEntity pushEntity, String url, CommunicatePlanEntityExt communicatePlanEntity) throws XbbException {
        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            throw new XbbException(MessageErrorCodeEnum.API_ERROR_380002);
        }

        SaveFakeProcessInstance instance = new SaveFakeProcessInstance();

        SaveFakeProcessInstanceRequest request = new SaveFakeProcessInstanceRequest();
        request.setTitle(XbbRefTypeEnum.COMMUNICATE_PLAN.getName());
        request.setAgentid(Long.valueOf(agentId));
        request.setProcess_code(dingtalkProcessCode);
        // 实例发起人暂定就使用ownerId，没什么大影响
        request.setOriginator_user_id(communicatePlanEntity.getOwnerId());
        request.setUrl(url);
        List<FormComponentValueVo> formComponentValueVoList = new ArrayList<>();
        JSONObject data = communicatePlanEntity.getData();
        // 执行时间
        if (data.containsKey(CommunicatePlanEnum.COMMUNICATE_TIME.getAttr())) {
            FormComponentValueVo timeComponetVo = new FormComponentValueVo();
            timeComponetVo.setName(CommunicatePlanEnum.COMMUNICATE_TIME.getAttrName());
            Long communicateTime = data.getLong(CommunicatePlanEnum.COMMUNICATE_TIME.getAttr());
            String timeValue = DateUtil.getString(communicateTime * 1000, new SimpleDateFormat("yyyy-MM-dd HH:mm"));
            timeComponetVo.setValue(timeValue);
            formComponentValueVoList.add(timeComponetVo);
        }
        // 客户名称
        if(data.containsKey(CommunicatePlanEnum.CUSTOMER_NAME_LINK_TEXT.getAttr())) {
            FormComponentValueVo customerComponetVo = new FormComponentValueVo();
            // 注意：客户名称使用 CUSTOMER_NAME_LINK_TEXT 关联客户隐藏 的值
            customerComponetVo.setName(CommunicatePlanEnum.LINK_CUSTOMER.getAttrName());
            customerComponetVo.setValue(data.getString(CommunicatePlanEnum.CUSTOMER_NAME_LINK_TEXT.getAttr()));
            formComponentValueVoList.add(customerComponetVo);
        }
        // 备注
        if(data.containsKey(CommunicatePlanEnum.MEMO.getAttr())) {
            FormComponentValueVo memoComponentVo = new FormComponentValueVo();
            memoComponentVo.setName(CommunicatePlanEnum.MEMO.getAttrName());
            memoComponentVo.setValue(data.getString(CommunicatePlanEnum.MEMO.getAttr()));
            formComponentValueVoList.add(memoComponentVo);
        }

        request.setForm_component_values(formComponentValueVoList);
        instance.setRequest(request);

        DingtalkWorkrecordHelper.ProcessInstanceResponse processInstanceResponse = null;
        try {
            processInstanceResponse = DingtalkWorkrecordHelper.createWorkrecordInstance(instance, accessToken);
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.createWorkrecordInstance 创建钉钉待办实例 失败：", e);
        }
        return processInstanceResponse;
    }

    /**
     * 创建钉钉待办任务
     * @param corpid
     * @return
     * @throws XbbException
     */
    @Override
    public DingtalkWorkrecordHelper.TaskResponse createWorkrecordTask(String corpid, String processInstanceId, String activityId, String url, List<UserEntity> userList) throws XbbException {

        String accessToken;
        String agentId;
        try {
            accessToken = authHelper.getAccessToken(corpid);
            agentId = authHelper.getAgentId(corpid, Env.DING_XBB_APP_ID);
        } catch (Exception e) {
            LOG.error("获取accessToken或agentId失败", e);
            throw new XbbException(MessageErrorCodeEnum.API_ERROR_380002);
        }

        SaveTask taskEntity = new SaveTask();
        SaveTaskRequest request = new SaveTaskRequest();
        request.setAgentid(Long.valueOf(agentId));
        request.setProcess_instance_id(processInstanceId);
        request.setActivity_id(activityId);
        List<TaskTopVo> tasks = new ArrayList<>();
        for (UserEntity user : userList) {
            TaskTopVo task = new TaskTopVo();
            task.setUserid(user.getUserId());
            task.setUrl(url);
            tasks.add(task);
        }
        request.setTasks(tasks);
        taskEntity.setRequest(request);

        DingtalkWorkrecordHelper.TaskResponse taskResponse = null;
        try {
            taskResponse = DingtalkWorkrecordHelper.createWorkrecordTask(taskEntity, accessToken);
        } catch (Exception e) {
            LOG.error("DingtalkWorkrecordMessageImpl.createWorkrecordTask 创建钉钉待办任务 失败：", e);
        }
        return taskResponse;
    }
}
